package slap.mvc.result;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import slap.Slap;
import slap.exception.UnexpectedException;
import slap.http.Request;
import slap.http.Response;
import slap.http.StatusCode;
import slap.mvc.scope.Flash;
import slap.mvc.scope.RenderModels;
import slap.mvc.scope.Session;
import slap.util.MimeTypes;

/**
 * 500 Error
 */
public class Error extends Result {
	protected static final Logger logger = LoggerFactory.getLogger(Error.class);
    private int status;

    public Error(String reason) {
        super(reason);
        this.status = StatusCode.INTERNAL_ERROR;
    }

    public Error(int status, String reason) {
        super(reason);
        this.status = status;
    }

    public void apply(Request request, Response response) {
        response.status = status;

        Map<String, Object> binding = RenderModels.current().data;
        binding.put("exception", this);
        binding.put("result", this);
        binding.put("session", Session.current());
        binding.put("request", Request.current());
        binding.put("flash", Flash.current());
        binding.put("play", new Slap());
        String errorHtml = "Error:" + getMessage();
        try {
            //errorHtml = TemplateLoader.load("errors/" + this.status + "." + (format == null ? "html" : format)).render(binding);
        } catch (Exception e) {
            logger.warn("Error page caused an error", e);
        }
        try {
            response.out.write(errorHtml.getBytes("utf-8"));
            response.disableGZipTransfer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
